class Solution1 {
    public int maxSubarraySumCircular(int[] nums) {
        int n = nums.length;
        int[] f = new int[n + 1]; // 最大的连续子数组
        int[] g = new int[n + 1]; // 最小的连续子数组

        int fRet = Integer.MIN_VALUE;
        int gRet = Integer.MAX_VALUE;

        int sum = 0;
        for (int x : nums) {
            sum += x;
        }

        for (int i = 1; i <= n; i++) {
            f[i] = Math.max(nums[i - 1], f[i - 1] + nums[i - 1]);
            fRet = Math.max(fRet, f[i]);
            g[i] = Math.min(nums[i - 1], g[i - 1] + nums[i - 1]);
            gRet = Math.min(gRet, g[i]);
        }

        return sum == gRet ? fRet : Math.max(fRet, sum - gRet);
    }
}